<template>
  <div class="content">
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <!-- 新增按钮 -->
      <div slot="header">
        <el-button
          type="primary"
          size="small"
          @click="add"
        >新增</el-button>
      </div>

      <div class="table-holder">
        <!-- 角色展示表格 -->
        <el-table :data="rolesList" border style="width: 100%">
          <el-table-column fixed="left" type="index" label="#" width="50" />
          <el-table-column prop="roleName" label="角色名称" width="200" />
          <el-table-column prop="roleCode" label="角色编码" width="200" />
          <el-table-column prop="remark" label="备注" />
          <el-table-column prop="createTime" label="添加时间" />
          <el-table-column fixed="right" label="操作" width="200">
            <template slot-scope="scope">
              <el-button
                type="success"
                size="small"
                @click="edit(scope.row)"
              >编辑</el-button>
              <el-button
                type="danger"
                size="small"
                @click="remove(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页器 -->
      <div class="pagination-holder">
        <el-pagination
          :current-page="page.start"
          :page-sizes="page.pageSize"
          :page-size="page.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增编辑橘色弹窗 -->
    <el-dialog title="编辑角色" :visible.sync="dialogFormVisible" width="30%">

      <el-form ref="roleInfo" :model="roleInfo" :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleInfo.roleName" />
        </el-form-item>
        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model="roleInfo.roleCode" />
        </el-form-item>
        <el-form-item label="角色描述" prop="remark">
          <el-input
            v-model="roleInfo.remark"
            type="textarea"
            placeholder="请输入内容"
            :rows="2"
          />
        </el-form-item>
        <el-form-item label="选择菜单" prop="remark">
          <el-row :gutter="20">
            <el-col :span="6" :offset="0">
              <el-checkbox v-model="expandAll">展开</el-checkbox>
            </el-col>
            <el-col :span="6" :offset="0">
              <el-checkbox v-model="selectAll">全选/反选</el-checkbox>
            </el-col>
          </el-row>

          <el-tree
            ref="tree"
            :data="permissionList"
            show-checkbox
            :default-expand-all="expandAll"
            node-key="id"
            highlight-current
            :props="defaultProps"
            @check="getNodes"
          />

        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button
          type="primary"
          @click="submit"
        >确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  requestRolesByPage,
  addRole,
  updataRole,
  deleteRole,
  requestRoleInfo,
  requestAllPermissions
} from '@/api/auth'
import mixin from '@/mixins/index'
export default {
  mixins: [mixin],
  data() {
    return {
      // 全选
      selectAll: false,
      // 是否展开全部
      expandAll: false,
      // 树形结构的参数
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      // 角色信息
      roleInfo: {
        permissionIds: []
      },
      // 角色列表
      rolesList: [],
      // 权限列表
      permissionList: [],
      dialogFormVisible: false,
      isAdd: false,
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    dialogFormVisible(val) {
      if (!val) {
        this.roleInfo = {}
      }
    },
    // 展开节点
    expandAll(val) {
      this.$nextTick(() => {
        for (var i = 0; i < this.$refs.tree.store._getAllNodes().length; i++) {
          this.$refs.tree.store._getAllNodes()[i].expanded = val
        }
      })
    },
    // 全选节点
    selectAll(val) {
      if (val) {
        this.$refs.tree.setCheckedNodes(this.permissionList)
      } else {
        this.$refs.tree.setCheckedKeys([])
      }
      this.roleInfo.permissionIds = this.$refs.tree.getCheckedKeys()
    }
  },
  created() {
    this.getRoleList()
    this.getPermissionList()
  },
  methods: {
    // 获取所有的节点
    getNodes(e, obj) {
      this.roleInfo.permissionIds = obj.checkedKeys
    },
    // 获取权限列表
    getPermissionList() {
      requestAllPermissions().then(res => {
        // console.log(res)
        this.permissionList = res.data.menus
      })
    },
    // 上传头像成功的钩子
    uploadSuccess(res) {
      // console.log(res)
      if (res.code === 20000) {
        this.$set(this.userInfo, 'salt', res.data.fileUrl)
      }
    },
    // 提交
    submit() {
      // console.log(this.userInfo)
      if (this.isAdd) {
        addRole(this.roleInfo).then(res => {
          if (res.code === 20000) {
            this.$message({
              type: 'success',
              message: '添加成功!'
            })
            this.dialogFormVisible = false
            this.$refs.tree.setCheckedKeys([])
            this.getRoleList()
          } else {
            this.$message({
              type: 'error',
              message: '添加失败!'
            })
          }
        })
      } else {
        updataRole(this.roleInfo).then(res => {
          // console.log(res)
          if (res.code === 20000) {
            this.$message({
              type: 'success',
              message: '修改成功!'
            })
            this.dialogFormVisible = false
            this.$refs.tree.setCheckedKeys([])
            this.getRoleList()
          } else {
            this.$message({
              type: 'error',
              message: '修改失败!'
            })
          }
        })
      }
    },
    // 关闭弹窗
    close() {
      this.dialogFormVisible = false
    },
    // 重置搜索结果
    resetSearch() {
      this.articleSearch = {
        title: '',
        author: ''
      }
      this.getUserList()
    },
    // 搜索
    search() {
      this.page.start = 0
      this.getUserList()
    },
    // 获取角色列表
    getRoleList() {
      requestRolesByPage(this.page).then((res) => {
        // console.log(res)
        this.page.total = res.data.total
        this.rolesList = res.data.rows
      })
    },
    // 弹出添加弹框
    // 新增角色
    add() {
      this.dialogFormVisible = true
      this.isAdd = true
    },
    // 编辑用户
    edit(item) {
      this.isAdd = false
      requestRoleInfo(item.id).then(res => {
        // console.log(res)
        this.roleInfo = res.data.role
        this.dialogFormVisible = true
        const list = this.roleInfo.permissionIds ? this.roleInfo.permissionIds : []
        this.$nextTick(() => {
          this.$refs.tree.setCheckedKeys(list)
        })
      })
    },
    // 改变每页数量
    handleSizeChange(val) {
      this.page.limit = val
      this.getUserList()
    },
    // 改变页码
    handleCurrentChange(val) {
      this.page.start = val
      this.getUserList()
    },
    // 删除
    remove(id) {
      // console.log(id)
      const _this = this
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteRole(id).then((res) => {
            // console.log(res);
            if (res.code === 20000) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              _this.getArticleList()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>

@import '@/style/index.scss'

<style scoped>
.avatar-uploader .el-upload {
  border-radius: 50%;
  border: 1px dashed #d9d9d9;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  border-radius: 50%;
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  line-height: 50px;
  text-align: center;
}
.avatar {
  border-radius: 50%;
  width: 50px;
  height: 50px;
  display: block;
}
</style>

<style lang="scss" scoped>
.content {
  .image {
    width: 100px;
    height: 100px;
  }

  .input-holder{
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 80%;

    span{
      width: 50px;
    }
  }
}
</style>
